import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import StatusError from './utils/StatusError';
import router from './router';
import { ValidationError } from 'sequelize';

const app = new Koa();

app.proxy = true;

export default app;

// Translate error into json response.
app.use((ctx, next) => {
  return next()
    .then(() => {
      if (__DEV__) {
        console.log(ctx.body);
      }
      ctx.body = ctx.body || { ok: 1 };
      ctx.body.ok = 1;
      ctx.body.result = ctx.body.result || ctx.result;
    }, err => {
      if (__DEV__) {
        console.error(err.stack);
      }
      const statusError = StatusError.from(err);
      ctx.status = statusError.status;
      ctx.body = statusError.toJson();
    });
});

app.use(bodyParser());

if (__DEV__) {
  app.use((ctx, next) => {
    console.log(ctx.url, ctx.request.body);
    return next();
  });
}

app.use(router.routes());

// TODO: 使用常量定义的异常
app.use(() => Promise.reject(new StatusError(404, 'Invalid API')));

export const listen = app.listen.bind(app);
